package com.lyc.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lyc.DTO.PostDTO;
import com.lyc.mapper.CommentMapper;
import com.lyc.mapper.PostMapper;
import com.lyc.mapper.InternshipJobsMapper;
import com.lyc.pojo.*;
import com.lyc.service.PostService;
import com.lyc.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class PostServiceImpl implements PostService {
    @Autowired
    private PostMapper postMapper;

    //实习、兼职
    @Autowired
    private InternshipJobsMapper internshipJobsMapper;

    //评论
    @Autowired
    private CommentMapper commentMapper;
    
    @Autowired
    private FileUploadService fileUploadService;

    @Value("${upload.path}")
    private String uploadPath;

    //添加帖子
    @Override
    public void addPostWithCover(Post post, MultipartFile[] coverFiles) throws IOException {
        // 设置当前用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        post.setUserId(userId);

        // 插入帖子信息
        postMapper.insert(post);
        
        // 获取刚插入的帖子ID
        Integer postId = post.getId();

        // 处理每个上传的文件
        for (int i = 0; i < coverFiles.length; i++) {
            MultipartFile file = coverFiles[i];
            if (!file.isEmpty()) {
                // 生成唯一文件名并保存
                String originalFilename = file.getOriginalFilename();
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                String fileName = UUID.randomUUID().toString() + extension;
                
                String normalizedUploadPath = uploadPath.replace("\\", "/");
                if (!normalizedUploadPath.endsWith("/")) {
                    normalizedUploadPath += "/";
                }
                
                // 创建上传目录
                File uploadDir = new File(normalizedUploadPath);
                if (!uploadDir.exists()) {
                    uploadDir.mkdirs();
                }
                
                String filePath = normalizedUploadPath + fileName;
                file.transferTo(new File(filePath));

                // 插入帖子图片信息
                PostImages postImage = new PostImages();
                postImage.setPostId(postId);
                postImage.setImageUrl("/uploads/" + fileName); // 保存图片的相对路径
                postImage.setSortOrder(i); // 设置排序字段
                postImage.setCreatedAt(post.getCreatedAt());
                postMapper.insertPostImages(postImage);
            }
        }
    }

    //获取所有帖子
    @Override
    public List<Post> getAllPosts() {
        List<Post> list = postMapper.getAllPosts();
        if (list != null) {
            return list;
        }
        return List.of();
    }

    //根据用户ID获取帖子列表
    @Override
    public List<Post> getPostsByUserId(Integer userId) {
        List<Post> list = postMapper.getPostsByUserId(userId);
        if (list != null) {
            return list;
        }
        return List.of();
    }

    //获取当前用户所有帖子信息
    @Override
    public PageBean<Post> getUserPostInfo(Integer pageNum, Integer pageSize) {
        //获取当前用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        //1.创建PageBean对象,用于封装分页数据
        PageBean<Post> pb = new PageBean<>();
        //2.开启分页查询 ->pageHelper(需要导入依赖)，有了pageHelper，就可以进行分页了，会自动拼接到sql，进行分页
        PageHelper.startPage(pageNum,pageSize);
        //3.调用mapper查询
        List<Post> as = postMapper.getUserPostInfo(userId);
        //Page中提供了方法，可以获取PageHelper分页查询后，得到的总记录条数和当前页数据
        //Page 是 PageHelper 提供的一个接口实现，封装了分页查询后的结果数据。
        Page<Post> p = (Page<Post>) as;
        //把数据填充到PageBean对象中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    //获取帖子详情
    @Override
    public Post getPostDetail(Integer id) {
        Post post = postMapper.getPostDetail(id);
        if (post != null) {
            return post;
        }
        return null;
    }
    
    // 增加帖子浏览次数（如果是实习/兼职信息，同时更新对应信息的浏览次数）
    @Transactional
    @Override
    public void incrementViewCount(Integer id) {
        // 更新帖子浏览次数
        postMapper.incrementViewCount(id);
        
        // 检查是否是实习/兼职信息
        Integer internshipJobId = postMapper.getInternshipJobIdByPostId(id);
        
        // 如果是实习/兼职信息，同时更新对应的浏览次数
        if (internshipJobId != null) {
            internshipJobsMapper.incrementViewCount(internshipJobId);
        }
    }

    //获取所有分类
    @Override
    public List<Category> getCategories() {
        List<Category> list = postMapper.getCategories();
        if (list != null) {
            return list;
        }
        return List.of();
    }

    //获取帖子封面
    @Override
    public List<PostImages> getCover() {
        List<PostImages> cover = postMapper.getCover();
        if (cover != null) {
            return cover;
        }
        return cover;
    }

    // 根据帖子ID获取封面图片
    @Override
    public List<PostImages> getCoverById(Integer postId) {
        List<PostImages> coverList = postMapper.getCoverById(postId);
        if (coverList != null) {
            return coverList;
        }
        return List.of();
    }

    //获取二手/失物帖子类型
    @Override
    public List<ItemType> getItemTypes(Integer categoryId) {
        List<ItemType> itemTypes = postMapper.getItemTypes(categoryId);
        if (itemTypes != null) {
            return itemTypes;
        }
        return List.of();
    }

    //获取二手/失物帖子列表--分页
    @Override
    public PageBean<Post> getItemList(Integer categoryId, Integer pageNum, Integer pageSize) {
        //1.创建PageBean对象,用于封装分页数据
        PageBean<Post> pb = new PageBean<>();
        //2.开启分页查询 ->pageHelper(需要导入依赖)，有了pageHelper，就可以进行分页了，会自动拼接到sql，进行分页
        PageHelper.startPage(pageNum,pageSize);
        //3.调用mapper查询
        List<Post> ps = postMapper.getItemList(categoryId);
        //Page中提供了方法，可以获取PageHelper分页查询后，得到的总记录条数和当前页数据
        //Page 是 PageHelper 提供的一个接口实现，封装了分页查询后的结果数据。
        Page<Post> p = (Page<Post>) ps;
        //把数据填充到PageBean对象中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    //获取二手/失物帖子列表--非分页
    @Override
    public List<Post> getItemLists(Integer categoryId) {
        List<Post> ps = postMapper.getItemLists(categoryId);
        if (ps != null) {
            return ps;
        }
        return List.of();
    }




    //获取热门帖
    @Override
    public List<Post> getHotPosts() {
        List<Post> posts = postMapper.getHotPosts();
        if (posts != null) {
            return posts;
        }
        return List.of();
    }

    // 按浏览量降序排序
    @Override
    public List<Post> selectAllOrderByViewCountDesc() {
        return postMapper.selectAllOrderByViewCountDesc();
    }

    //修改帖子封面--阿里云
//    @Override
//    public String uploadCover(MultipartFile file) throws Exception {
//        // 获取原始文件名
//        String originalFilename = file.getOriginalFilename();
//        // 截取文件后缀
//        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
//        // 构造新文件名
//        String objectname = UUID.randomUUID().toString() + extension;
//        // 文件的路径
//        return AliOssutil.uploadFile(objectname,file.getInputStream());
//    }

    //修改帖子封面--本地存储
    @Override
    public String uploadCover(MultipartFile file, Integer postId) throws IOException {
        String normalizedUploadPath = uploadPath.replace("\\", "/");
        if (!normalizedUploadPath.endsWith("/")) {
            normalizedUploadPath += "/";
        }

        // 生成唯一文件名并保存
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + extension;

        String filePath = normalizedUploadPath + fileName;
        file.transferTo(new File(filePath));

        // 更新帖子图片信息
        postMapper.updateCover("/uploads/" + fileName, postId);
        return "/uploads/" + fileName;
    }

    //修改帖子信息
    @Override
    public void update(PostDTO postDTO) {
        postMapper.update(postDTO);
    }

    // 批量/单个修改帖子状态
    @Override
    public void batchUpdatePostStatus(List<Integer> postIds, String status) {
        for (Integer postId : postIds) {
            Post post = new Post();
            post.setId(postId);
            post.setStatus(status);
            postMapper.updatePostStatus(post);
        }
    }

    // 删除帖子封面
    @Override
    public void deleteCover(Integer id) {
        // 先获取要删除的图片信息
        PostImages postImage = postMapper.getPostImageById(id);
        if (postImage != null) {
            // 获取图片的相对路径
            String imageUrl = postImage.getImageUrl();
            
            // 构建图片在服务器上的完整路径
            String normalizedUploadPath = uploadPath.replace("\\", "/");
            if (!normalizedUploadPath.endsWith("/")) {
                normalizedUploadPath += "/";
            }
            
            // 从imageUrl中提取文件名
            String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
            String filePath = normalizedUploadPath + fileName;
            
            // 删除物理文件
            File imageFile = new File(filePath);
            if (imageFile.exists()) {
                boolean deleted = imageFile.delete();
                if (!deleted) {
                    System.out.println("删除图片文件失败: " + filePath);
                }
            } else {
                System.out.println("图片文件不存在: " + filePath);
            }
        } else {
            System.out.println("未找到ID为 " + id + " 的帖子封面");
        }
        
        // 删除数据库记录
        postMapper.deleteCover(id);
    }

    // 删除用户帖子
    @Override
    public void deletePost(Integer id) {
        // 先删除帖子关联的图片文件
        List<PostImages> postImages = postMapper.getCoverById(id);
        if (postImages != null && !postImages.isEmpty()) {
            String normalizedUploadPath = uploadPath.replace("\\", "/");
            if (!normalizedUploadPath.endsWith("/")) {
                normalizedUploadPath += "/";
            }
            
            for (PostImages image : postImages) {
                // 获取图片的相对路径
                String imageUrl = image.getImageUrl();
                
                // 从imageUrl中提取文件名
                String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
                String filePath = normalizedUploadPath + fileName;
                
                // 删除物理文件
                File imageFile = new File(filePath);
                if (imageFile.exists()) {
                    boolean deleted = imageFile.delete();
                    if (!deleted) {
                        System.out.println("删除图片文件失败: " + filePath);
                    }
                } else {
                    System.out.println("图片文件不存在: " + filePath);
                }
            }
        }
        
        // 删除帖子相关的图片记录
        postMapper.deletePostImagesByPostId(id);

        // 删除帖子关联的评论
        commentMapper.deleteByPostId(id);
        
        // 删除帖子
        postMapper.deletePost(id);
    }
    
    // 根据用户ID删除帖子及相关数据
    @Override
    @Transactional
    public void deletePostsByUserId(Integer userId) {
        // 获取用户的所有帖子
        List<Post> posts = postMapper.getPostsByUserId(userId);
        
        // 删除每个帖子及其相关数据
        for (Post post : posts) {
            deletePost(post.getId());
        }
    }
}